<?php
namespace DaChongQing\Controller;
use Think\Controller;
class QrcodeController extends Controller{
    public function UserQRcode(){
        if(I('code') == ''){
            $this->redirect('Qrcode/code');
        }
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".C('APPID')."&secret=".C('APPSECRET')."&code=".I('code')."&grant_type=authorization_code";
        $arr = json_decode(file_get_contents($url));
        $openid = $arr->openid;
        cookie('openid',$openid);
        $nickname = M('user_qrcode')->where(array('openid'=>$openid))->find();
        $user = M('user_info')->where(array('openid'=>$openid))->find();
        cookie('nickname',$user['nickname']);
        $this->nickname = $user['nickname'];
        $this->QrcodeUrl = $nickname['url'];
        $this->remark = C('REMARK_BONUS');
        $this->userinfo = M('user_info')->where(array('from' => $openid))->select();
        $this->share = U("Qrcode/share/",array('openid'=>$openid),true,true);
        $this->display();
    }

    public function share(){
        $openid = I('openid');
        $nickname = M('user_qrcode')->where(array('openid'=>$openid))->find();
        $user = M('user_info')->where(array('openid'=>$openid))->find();
        $this->nickname = $user['nickname'];
        $this->openid = $openid;
        $this->QrcodeUrl = $nickname['url'];
        $this->remark = C('REMARK_BONUS');
        $this->display();
    }

    public function code(){
        getCode(U('Qrcode/UserQRcode','',true,true),C('APPID'));
    }

    public function MakeQRcode(){
        $this->display();
    }

    public function ti(){
       echo self::SetQRcode('1438826927');
    }
    /**
     * @param $rand_area 场景参数
     * @param $action_name
     */
    public function SetQRcode($rand_area,$action_name = "QR_LIMIT_SCENE"){
        $access_token = AccessToken();
        $get_msg_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token;
        $postMsg = array(
            'action_name' => $action_name,
            'action_info' => array(
                'scene' => array(
                    'scene_id' => $rand_area
                )
            )
        );
        $postJson = json_encode($postMsg);
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_msg_url);
        curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch,CURLOPT_AUTOREFERER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$postJson);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        $info = curl_exec($ch);
        if(curl_errno($ch)) echo "Error".curl_error($ch);
        curl_close($ch);
        $arrInfo = json_decode($info);
        $url =urlencode($arrInfo->ticket);
        $getQRcodeUrl = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$url;
        return $getQRcodeUrl;
    }

    public function add(){
        if(!IS_AJAX || cookie('openid') == ''){
            $this->redirect('Qrcode/UserQRcode');
        }
        $qrcode = array(
            'parameter' => "用户推广二维码",
            'use' => 1
        );
        $id = M('qrcode_repertory')->data($qrcode)->add();
        $url = self::SetQRcode($id);
        $data = array(
            'url' => $url
        );
        M('qrcode_repertory')->where(array('id'=>$id))->save($data);
        $result = M('qrcode_repertory')->where(array('id'=>$id))->find();
        $data = array(
            'openid' => cookie('openid'),
            'nickname' => cookie('nickname'),
            'scan' => 0,
            'url' => $result['url'],
            'time' => time(),
            'qid' => $id
        );
        M('user_qrcode')->data($data)->add();
        $this->ajaxReturn($result['url'],'EVAL');
    }

    public static function SendBonus($openid,$bonus){
        if($openid == '' || $bonus == ''){
            die('参数错误');
        }else{
        $pay = new BonusController($openid,$bonus);
        $md5sign = $pay->SetSign();
        $parameters = array(
            'nonce_str' => '123123131231321',
            'sign' => $md5sign,
            'mch_billno' => $pay->wxMchBillno('1252370801'),
            'mch_id' => C('MCH_ID'),
            'wxappid' => 'wx22c589512a2d5f61',
            'nick_name' => '我爱大重庆',
            'send_name' => '我爱大重庆',
            're_openid' => $openid,
            'total_amount' => $bonus,
            'min_value' => $bonus,
            'max_value' => $bonus,
            'total_num' => '1',
            'wishing' => '恭喜发财！',
            'client_ip' => '121.40.30.107',
            'act_name' => '恭喜发财',
            'remark' => '恭喜发财'
        );
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        $send = $pay->wxHttpsRequestPem($url,$pay->wxArrayToXml($parameters));
            $arr = xml_to_array($send);
        $user = M('user_info')->where(array('openid'=>$openid))->find();
        $data = array(
            'openid' => $openid,
            'bonusname' => ($bonus/100)."元红包",
            'nickname' => $user['nickname'],
            'time' => time(),
            'type' => '3'
        );
        M('user_bonus')->data($data)->add();
            S('bonus',null);
            return $arr;
    }
    }

    /**
     * 神兽，待我来召唤你，二维码批量生成
     */
    public function CreateQRcode(){
        header("Content-type:text/html;charset=utf-8");
//        $qrcode = array(
//            'parameter' => "内部或者线下二维码",
//            'use' => 1
//        );
//        for ($i = 1;$i <= 20 ; $i++){
//            $id = M('qrcode_repertory')->data($qrcode)->add();
//            $url = self::SetQRcode($id);
//            $data = array(
//                'url' => $url
//            );
//            M('qrcode_repertory')->where(array('id'=>$id))->save($data);
//        }
        $result = M('qrcode_repertory')->where(array('parameter' => "内部或者线下二维码"))->select();
        $a = '';
        echo "<div style='width:1200px;margin:0 auto'><H4 style='text-align: center'>线下推广二维码</H4>";
        foreach ($result as $k => $v){
            echo "<div style='width:200px;float:left;'>
                        <img style='width: 100%' src='".$result[$k]['url']."'>
                        <p style='text-align:center'>SceneId_".$result[$k]['id']."</p>
                    </div>
                    ";
        }
        echo "</div>";
    }

}